from playwright.sync_api import Page

'''
获取选择器中的TEXT
@Auth k1919
'''
def get_selector_text(page: Page, selector: str) -> str | None:
    try:

        # 等待元素出现在DOM且可见  
        element = page.wait_for_selector(
            selector,
            state='attached',  # 确保元素已附加到DOM  
            timeout=8000  # 5秒超时
        )
        # 获取去空格后的文本  
        return element.inner_text().strip()

    except Exception as e:
        print(f"元素获取失败: {selector} | 错误: {str(e)}")
        return None

def get_selector_src(page: Page, selector: str) -> str | None:
    try:

        # 等待元素出现在DOM且可见
        element = page.wait_for_selector(
            selector,
            state='visible',  # 确保元素已附加到DOM
            timeout=8000  # 5秒超时
        )
        return element.get_attribute("src")

    except Exception as e:
        print(f"元素获取失败: {selector} | 错误: {str(e)}")
        return None

def get_selector_href(page: Page, selector: str) -> str | None:
    try:

        # 等待元素出现在DOM且可见
        element = page.wait_for_selector(
            selector,
            state='attached',  # 确保元素已附加到DOM
            timeout=8000  # 5秒超时
        )
        # 获取去空格后的文本
        return element.get_attribute("href")

    except Exception as e:
        print(f"元素获取失败: {selector} | 错误: {str(e)}")
        return None
